package leecode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname
 * @Description TODO
 * @Date 2021/7/26 21:02
 * @Created by Alberthch
 * 题目：得到子序列的最少操作次数
 */
class Solution_1713 {
    public static int minOperations(int[] target, int[] arr) {
        int n = target.length;
        Map<Integer, Integer> pos = new HashMap<Integer, Integer>();
        for (int i = 0; i < n; ++i) {
            pos.put(target[i], i);
        }
        List<Integer> d = new ArrayList<Integer>();
        for (int val : arr) {
            if (pos.containsKey(val)) {

                int idx = pos.get(val);
                int it = binarySearch(d, idx);
                // 不等于就是更新值
                if (it != d.size()) {
                    d.set(it, idx);
                } else {
                    // 等于就是增加值
                    d.add(idx);
                }
            }
        }
        return n - d.size();
    }

    // 辅助函数，找到i，其中d[i-1] < target <d[i]
    public static int binarySearch(List<Integer> d, int target) {
        int size = d.size();

        // 该情形进行d数组的增加元素，并且len+1
        if (size == 0 || d.get(size - 1) < target) {
            return size;
        }

        // 二分查找
        int low = 0, high = size - 1;
        // 终止条件，low == high
        while (low < high) {
            int mid = (high - low) / 2 + low;
            if (d.get(mid) < target) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;
    }


    public static void main(String[] args) {
        int[] target1 = new int[]{5,1,3};
        int[] arr1 = new int[]{9,4,2,3,4};
        System.out.println(minOperations(target1,arr1));

        int[] target2 = new int[]{6,4,8,1,3,2};
        int[] arr2 = new int[]{4,7,6,2,3,8,6,1};
        System.out.println(minOperations(target2,arr2));
    }
}
